from urllib.parse import urljoin
from typing import Any
from dify_plugin import ToolProvider
import requests


class DatToolProvider(ToolProvider):
    def _validate_credentials(self, credentials: dict[str, Any]) -> None:
        base_url = credentials["base_url"]
        if not base_url:
            raise ValueError("Please fill in the DAT OpenAPI Server base url")

        timeout = credentials["timeout"]
        if timeout is None or timeout.strip() == "" or not timeout.isdigit():
            raise ValueError("Timeout can be empty or fill with integer value")

        url = urljoin(base_url.rstrip('/') + '/', 'health')

        headers = {
            'accept': 'application/json'
        }

        try:
            response = requests.get(url,headers=headers, timeout=int(timeout))
        except Exception as e:
            raise ValueError(f"DAT OpenAPI Server invoke failed: {e}")

        if response.status_code != 200:
            if response.status_code == 401:
                raise ValueError("DAT OpenAPI Server invoke authorization error")
            elif response.status_code == 429:
                raise ValueError("DAT OpenAPI Server invoke rate limit error")
            elif response.status_code == 500:
                raise ValueError("DAT OpenAPI Server invoke server unavailable error")
            else:
                raise ValueError("DAT OpenAPI Server invoke bad request error")
